#include "cat-server.hpp"
#include <iostream>

CATSERVER::CatServer::CatServer():
	isRun(false),
	DisconnectEvt(NULL),
	ReceivedDataEvt(NULL),
	LogMessageEvt(NULL),
	server(NULL)
{
}

CATSERVER::CatServer::~CatServer()
{
}

void CATSERVER::CatServer::StartServer(int port)
{
	if (!isRun) {
		isRun = true;
		server_port = port; 
		server = new std::thread(&CatServer::ReceiveMessageLoop, this);
	}
}

void CATSERVER::CatServer::StopServer()
{
	_disconnect();
	server->join();
	server = NULL;
}


void CATSERVER::CatServer::ReceiveMessageLoop()
{
	listener.listen(server_port);	
	char buffer[4096];

	std::size_t received = 0;
	while (isRun)
	{	
		int offset = 0;
		sf::TcpSocket socket;
		listener.accept(socket);
		while(socket.receive(buffer, sizeof(buffer), received)== sf::Socket::Done) 
		{
			while (offset>=0)
			{
				ProtocolInfo *pInfo= GetProtocolInfo(buffer+ offset,12);
				if (pInfo->PacketLength < 12 || pInfo->PacketLength>(4096-offset)) {
					free(pInfo);
					break;
				}
				if (offset + pInfo->PacketLength > received)
				{
					free(pInfo);
					break;
				}
				int payLoadSize = pInfo->PacketLength - 12;
				ProcessData(pInfo->Action,buffer+offset + 12, payLoadSize);
				offset += pInfo->PacketLength;
				free(pInfo);			
			}
		}
	}
}

void CATSERVER::CatServer::ProcessData(int action, char* buffer, int size)
{
		if (ReceivedDataEvt)
			ReceivedDataEvt(action,buffer, size);
}

void CATSERVER::CatServer::_disconnect()
{
	if (isRun) {
		isRun = false;
		listener.close();
		if (DisconnectEvt)
			DisconnectEvt();
	}
}
